//
//  WNRecommendVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/8/7.
//

import UIKit

let scro_h: CGFloat = (ScreenW-36)*0.5*1.55+70

class WNRecommendVC: WNBaseVC {
    
    lazy var searchView: WNSearchView = {
        let view = WNSearchView()
        view.searchType(0)
        return view
    }()
    
    lazy var recColView: UICollectionView = {
        let layout = WaterFallLayout()
        layout.watefallColumns = 2
        layout.scrollDirection = .vertical
        layout.delegate = self
        layout.sectionInset = .init(top: 8, left: 8, bottom: 8, right: 8)
        let col = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        col.showsVerticalScrollIndicator = false
        col.showsHorizontalScrollIndicator = false
        col.backgroundColor = .white
        col.delegate = self
        col.dataSource = self
        col.register(RecColCell.self, forCellWithReuseIdentifier: RecColCell.identifier)
        col.ly_emptyView = WNEmptyView.wn_loadStyle(descStr: .recommend, imageStr: .recommend, tapBlock: { [weak self] in
            col.mj_header?.beginRefreshing()
        })
        col.isHidden = true
        return col
    }()
    
    var recArr = [BookDetailModel]()
    
    // 滑动偏移量
    var offsetY = CGFloat()
    // 上次滑动偏移量
    var lastOffsetY = CGFloat()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        searchView.readImage.isHidden = getHasCheck()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        wn_hidNavView()
        view.addSubview(searchView)
        view.addSubview(recColView)
        searchView.snp.makeConstraints { (make) in
            make.top.equalTo(StatusBarHeight)
            make.left.right.equalTo(0)
            make.height.equalTo(44)
        }
        recColView.snp.makeConstraints { make in
            make.top.equalTo(searchView.snp.bottom)
            make.left.right.equalTo(0)
            make.bottom.equalTo(-TabBarTotalHeight)
        }
    }
    
    override func dataConfig() {
        pageName = "Recommend"
        listSettingRefresh()
        getRecRequest()
    }
    
    override func handleNoti() {
        NotificationCenter.default.addObserver(forName: WNNotiName.loginNoti, object: nil, queue: nil) { [weak self] not in
            self?.getRecRequest()
        }
    }
}

extension WNRecommendVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        recArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RecColCell.identifier, for: indexPath) as! RecColCell
        cell.model = recArr[indexPath.item]
        cell.desLabel.numberOfLines = 0
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        wn_pushBookVC(recArr[indexPath.item].bookId ?? "")
    }
}

extension WNRecommendVC: WaterfallLayoutDelegate {
    
    func waterFlowLayout(_ layout: WaterFallLayout, _ indexPath: IndexPath, _ width: CGFloat) -> CGFloat {
        return (ScreenW-36)*0.5*1.55 + wn_getTextHeigh(textStr: recArr[indexPath.item].name ?? "", font: .wn_font(name: .bold, size: 14), width: width, lineSpace: 0) + wn_getTextHeigh(textStr: recArr[indexPath.item].des ?? "", font: .wn_font(name: .bold, size: 11), width: width, lineSpace: 0) + 32
    }
}

extension WNRecommendVC {
    
    func listSettingRefresh() {
        recColView.mj_header = wn_refreshHeader(completion: { [weak self] in
            self?.page = 1
            self?.hasPage = false
            self?.getRecRequest()
        })
        
        recColView.mj_footer = wn_refreshFooter(completion: { [weak self] in
            if self?.page == 1 && (self?.recArr.count ?? 0) == 0 {
                self?.recColView.mj_footer?.endRefreshing()
                return
            }
            if self?.hasPage == true {
                self?.page += 1
                self?.getRecRequest()
            }else {
                self?.recColView.mj_footer?.endRefreshingWithNoMoreData()
            }
        })
    }
}

extension WNRecommendVC {
    
    func getRecRequest() {
        WNHUD.wn_showLoading()
        provider_recommend.rx.request(.recommend(page))
            .asObservable().mapModel(BaseModel<[BookDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                WNHUD.wn_hide()
                self?.recColView.isHidden = false
                self?.recColView.ly_emptyView.imageStr = EmptyImage.recommend.rawValue
                self?.recColView.ly_emptyView.detailStr = EmptyDesc.recommend.rawValue
                self?.recColView.ly_emptyView.btnTitleStr = ""
                guard model.code == 0 else {
                    if (self?.isFirst ?? true) {
                        self?.recColView.ly_emptyView.imageStr = EmptyImage.serverBad.rawValue
                        self?.recColView.ly_emptyView.detailStr = EmptyDesc.serverBad.rawValue
                        self?.recColView.ly_emptyView.btnTitleStr = "Click Refresh"
                    }else {
                        self?.wn_toast(model.msg ?? "")
                    }
                    self?.recColView.mj_header?.endRefreshing()
                    self?.recColView.mj_footer?.endRefreshing()
                    self?.isFirst = false
                    return
                }
                if self?.page == 1 {
                    self?.recArr.removeAll()
                    self?.recColView.mj_footer?.resetNoMoreData()
                }
                if let arr = model.data {
                    self?.hasPage = arr.count > 17
                    self?.recArr += arr
                }else {
                    self?.recColView.mj_footer?.endRefreshingWithNoMoreData()
                }
                self?.recColView.reloadData()
                self?.recColView.mj_header?.endRefreshing()
                self?.recColView.mj_footer?.endRefreshing()
                self?.isFirst = false
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
                self?.recColView.ly_emptyView.imageStr = EmptyImage.netWork.rawValue
                self?.recColView.ly_emptyView.detailStr = EmptyDesc.netWork.rawValue
                self?.recColView.ly_emptyView.btnTitleStr = "Click Refresh"
                self?.recColView.mj_header?.endRefreshing()
                self?.recColView.mj_footer?.endRefreshing()
                self?.recColView.isHidden = false
            }).disposed(by: rx.disposeBag)
    }
}
